import {reqCodeNum,reqUserLogin,reqLogin,reqGetUserInfo,reqLoginOut} from '@/api'
import {setToken,clearToken} from '@/utils/token'
const state = {
  // 初始值
  code:' ',
  userInfo:{},
  token:localStorage.getItem('TOKEN')
};
const mutations = {
   GWTCODENUM(state,code){
     state.code = code
   },
   LOGIN(state,token){
     state.token = token 
   },
   GETUSERINFO  (state,userInfo){
     state.userInfo = userInfo
   },
   CLEARUSERINFO(state){
     state.userInfo = '';
     state.token = '';
     clearToken()
   }
};
const actions = {
  async getCodeNum(context,phoneNum){
    let res = await reqCodeNum(phoneNum)
    if(res.code == 200){
      context.commit("GWTCODENUM",res.data) 
      return 'ok'
    }else {
      return Promise.reject(new Error('失败了！'))
    }
  }, 
  // 用户注册
  async userLogin(context,{user}){
    let res = await reqUserLogin(user)
    console.log(res);
    if(res.code == 200){
      return 'ok'
    }else {
      return Promise.reject(new Error('失败了！'))
    }
  },
  // 登录
  async login(context,{data}){
    console.log(data);
    let res = await reqLogin(data)
    console.log(res);
    if(res.code == 200){
      context.commit("LOGIN",res.data.token) 
      // 持久化存储token
      setToken(res.data.token)
      return 'ok' 
    }else {
      return Promise.reject(new Error('失败了！'))
    }
  },
  // 获取用户信息reqGetUserInfo
  async getUserInfo(context){
    let res = await reqGetUserInfo()
    if(res.code == 200){
      context.commit('GETUSERINFO',res.data)
    }else {
      return Promise.reject(new Error('失败了！'))
    }
  },
  // 退出登录
  async loginOut(context){
    let res = await reqLoginOut()
    if(res.code == 200){
      context.commit('CLEARUSERINFO')
      return 'ok'
    }else {
      return Promise.reject(new Error('失败了！'))
    }
  }

};
const getters = { };
export default {
  state,
  mutations,
  actions,
  getters
}